/*
 * Copyright (c) 2016-2018 Hunan CNBOT Co., Ltd. All Rights Reserved.
 * FileName: CnbotsThreadPools.java
 * @author: Clintonfang
 * @date: 18-12-11 下午2:14
 * @version: 1.0
 */

package com.cnbot.toolkit.log.zlog;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.cnbot.toolkit.threadpool.ThreadUtil.threadFactory;

/**
 * 线程池类
 * @author ww
 * @date 2018-12-11 15:27:55
 */
public class LogThreadPools {

	/**
	 * 数据读取和写入线程池
	 */
	public final ScheduledThreadPoolExecutor iOScheduledThreadPool;

	/**
	 * 添加到阻塞队列的阻塞线程
	 */
	public final ThreadPoolExecutor blockThreadFactoryPool;

	private LogThreadPools() {
		ThreadFactory blockThreadFactory = threadFactory("blockThreadFactoryPool", true);
		blockThreadFactoryPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), blockThreadFactory);
		ThreadFactory iOThreadFactory = threadFactory("iOThreadFactory", true);
		iOScheduledThreadPool = new ScheduledThreadPoolExecutor(2, iOThreadFactory);
	}

	public static LogThreadPools getInstance() {
		return SingletonHolder.INSTANCE;
	}

	/**
	 * 在程序退出时，统一释放
	 */
	public void releaseThreadPool() {
		shutdownNow(iOScheduledThreadPool, blockThreadFactoryPool);
	}

	private void shutdown(ThreadPoolExecutor... executors) {
		if (executors == null || executors.length == 0) {
			return;
		}
		for (ThreadPoolExecutor poolExecutor : executors) {
			poolExecutor.shutdown();
		}
	}

	private void shutdownNow(ThreadPoolExecutor... executors) {
		if (executors == null || executors.length == 0) {
			return;
		}
		for (ThreadPoolExecutor poolExecutor : executors) {
			poolExecutor.shutdownNow();
		}
	}

	private static class SingletonHolder {
		private static final LogThreadPools INSTANCE = new LogThreadPools();
	}
}
